package com.example.za.account.fragment;


import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.borax12.materialdaterangepicker.date.DatePickerDialog;
import com.example.za.account.R;
import com.example.za.account.adapter.CommonAdapter;
import com.example.za.account.application.AccountApplication;
import com.example.za.account.dao.IncomeDao;
import com.example.za.account.model.IncomeStatistics;
import com.example.za.account.utils.DateUtils;
import com.example.za.account.utils.FormatUtils;
import com.example.za.account.view.NoScrollListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.PieChartView;

public class PieIncomeFragment extends BaseFragment implements DatePickerDialog.OnDateSetListener {

    @BindView(R.id.label_date_chart)
    TextView labelDateChart;
    @BindView(R.id.pie_chart)
    PieChartView pieChart;
    @BindView(R.id.list_chart)
    NoScrollListView listChart;
    Unbinder unbinder;
    private View rootView;
    private IncomeDao mIncomeDao;
    private PieChartData mPieChartData;
    private int mMonth;
    private int mYear;
    private int[] mArcQueue;
    private CommonAdapter mCommonAdapter;
    private List<IncomeStatistics> mIncomeStatisticses;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mIncomeDao = new IncomeDao(getActivity());
        Calendar instance = Calendar.getInstance();
        mMonth = instance.get(Calendar.MONTH);
        mYear = instance.get(Calendar.YEAR);
        mPieChartData = new PieChartData();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = super.onCreateView(inflater, container, savedInstanceState);
            unbinder = ButterKnife.bind(this, rootView);
            //创建饼状图并设置图标颜色、文字颜色、字体大小、中心文字等属性。
            mPieChartData.setHasCenterCircle(true);
            mPieChartData.setCenterText1FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                    (int) getResources().getDimension(R.dimen.pie_chart_text1_size)));
            mPieChartData.setCenterText2FontSize(ChartUtils.px2sp(getResources().getDisplayMetrics().scaledDensity,
                    (int) getResources().getDimension(R.dimen.pie_chart_text2_size)));
            mPieChartData.setCenterText1Color(getResources().getColor(R.color.gray_holo_dark));
            mPieChartData.setCenterText2Color(getResources().getColor(R.color.gray_holo_dark));
            mPieChartData.setHasLabels(true);
            mPieChartData.setHasLabelsOutside(false);
            mPieChartData.setHasLabelsOnlyForSelected(false);
            pieChart.setValueSelectionEnabled(true);
            pieChart.setCircleFillRatio(1.0f);
            updateData(DateUtils.getMonthStart(mYear, mMonth), DateUtils.getMonthEnd(mYear, mMonth));

        }

        // 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;

    }

    public void updateData(Date monthStart, Date monthEnd) {
        String label;
        if (mYear < Calendar.getInstance().get(Calendar.YEAR)) {
            label = DateUtils.date2Str(monthStart, "yyyy年MM月dd日") + " - " + DateUtils.date2Str(monthEnd, "dd日");
        } else {
            label = DateUtils.date2Str(monthStart, "MM月dd日") + " - " + DateUtils.date2Str(monthEnd, "dd日");
        }
        labelDateChart.setText(label);
        pieChart.setOnValueTouchListener(new ValueTouchListener());
        mIncomeStatisticses = mIncomeDao.getPeriodCatSumIncome(monthStart, monthEnd, AccountApplication.sUser.getmId());
        if (mIncomeStatisticses != null && mIncomeStatisticses.size() > 0) {
            List<SliceValue> sliceValueList = new ArrayList<>(mIncomeStatisticses.size());
            mPieChartData.setCenterText1("总收入");
            float sumIncome = mIncomeDao.getPeriodSumIncome(monthStart, monthEnd, AccountApplication.sUser.getmId());
            mPieChartData.setCenterText2(String.valueOf(sumIncome));
            for (int i = 0, j = mIncomeStatisticses.size(); i < j; i++) {
                sliceValueList.add(new SliceValue(mIncomeStatisticses.get(i).getmSum(), ChartUtils.nextColor()));
            }
            mPieChartData.setValues(sliceValueList);
        } else {
            mPieChartData.setValues(null);
            mPieChartData.setCenterText1(getString(R.string.info_empty));
            mPieChartData.setCenterText2("");
        }
        pieChart.setPieChartData(mPieChartData);
        prepareDataAnimation();
        pieChart.startDataAnimation();
        if (mCommonAdapter == null) {
            mCommonAdapter = new CommonAdapter<IncomeStatistics>(mIncomeStatisticses, R.layout.item_chart_statistic) {
                @Override
                public void bindView(ViewHolder holder, IncomeStatistics obj) {
                    holder.setText(R.id.item_label_amount_chart_list, String.valueOf(obj.getmSum()));
                    holder.setText(R.id.item_label_percent_chart_list, String.valueOf(obj.getmPercent() + "%"));
                    holder.setImageResource(R.id.item_icon_chart_list, obj.getmIncomeCat().getmImageId());
                    holder.setText(R.id.item_label_category_chart_list, obj.getmIncomeCat().getmName());
                }
            };
            listChart.setAdapter(mCommonAdapter);
        } else {
            mCommonAdapter.setmData(mIncomeStatisticses);
        }
        pieChart.setFocusable(true);
        pieChart.setFocusableInTouchMode(true);
        pieChart.requestFocus();

    }

    private void prepareDataAnimation() {
        List<SliceValue> values = mPieChartData.getValues();
        int mIndex = (int) (Math.random() * values.size());
        mArcQueue = new int[values.size()];
        for (int i = 0, j = values.size(); i < j; i++) {
            if (mIndex >= j - 1) {
                mIndex = 0;
            } else {
                mIndex++;
            }
            mArcQueue[i] = mIndex;
            values.get(i).setTarget(values.get(mIndex).getValue());
        }

    }

    @Override
    protected Fragment getSubFragment() {
        return this;
    }

    @Override
    protected int getResId() {
        return R.layout.fragment_pie;
    }


    @Override
    public void onResume() {
        super.onResume();
        mMonth = Calendar.getInstance().get(Calendar.MONTH);
        DatePickerDialog dpd = (DatePickerDialog) getActivity().getFragmentManager().findFragmentByTag("DatePickerDialog");
        if (dpd != null) {
            dpd.setOnDateSetListener(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @OnClick({R.id.icon_chart_left, R.id.label_date_chart, R.id.icon_chart_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.icon_chart_left: {
                mMonth--;
                if (mMonth < 0) {
                    mMonth = mMonth + 12;
                    if ((mMonth + 1) % 12 == 0) {
                        mYear--;
                    }
                }
                updateData(DateUtils.getMonthStart(mYear, mMonth), DateUtils.getMonthEnd(mYear, mMonth));
            }
            break;
            case R.id.label_date_chart: {
                DatePickerDialog dpd = DatePickerDialog.newInstance(this, mYear, mMonth, 1);
                dpd.setStartTitle("开始日期");
                dpd.setEndTitle("结束日期");
                dpd.setThemeDark(true);
                dpd.setAccentColor(getResources().getColor(R.color.colorPrimary));
                dpd.show(getActivity().getFragmentManager(), "DatePickerDialog");
            }
            break;
            case R.id.icon_chart_right: {
                Calendar calendar = Calendar.getInstance();
                if (mYear == calendar.get(Calendar.YEAR) && mMonth == calendar.get(calendar.MONTH)) {
                    return;
                }
                mMonth++;
                if (mMonth > 11) {
                    mMonth = mMonth - 12;
                    mYear++;
                }
                updateData(DateUtils.getMonthStart(mYear, mMonth), DateUtils.getMonthEnd(mYear, mMonth));
            }
            break;
        }
    }

    @Override
    public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth, int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
        Calendar start = Calendar.getInstance();
        start.set(Calendar.YEAR, year);
        start.set(Calendar.MONTH, monthOfYear);
        start.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        Calendar end = Calendar.getInstance();
        end.set(Calendar.YEAR, yearEnd);
        end.set(Calendar.MONTH, monthOfYearEnd);
        end.set(Calendar.DAY_OF_MONTH, dayOfMonthEnd);
        updateData(start.getTime(), end.getTime());
    }

    private class ValueTouchListener implements PieChartOnValueSelectListener {
        @Override
        public void onValueSelected(int arcIndex, SliceValue value) {
            String s = value.toString();
            s = s.substring(s.indexOf("=") + 1, s.indexOf("]"));
            float amount = FormatUtils.formatFloat("########.#", Float.parseFloat(s));
            mPieChartData.setCenterText1(mIncomeStatisticses.get(mArcQueue[arcIndex]).getmIncomeCat().getmName());
            mPieChartData.setCenterText2(String.valueOf(amount));
        }

        @Override
        public void onValueDeselected() {

        }
    }

}
